package com.shop.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.common.core.domain.Result;
import com.shop.product.domain.*;
import com.shop.product.mapper.ItemMapper;
import com.shop.product.service.*;
import com.shop.product.vo.ItemGroupBaseAttoVo;
import com.shop.product.vo.ItemInfo;
import com.shop.product.vo.ItemSaleAttr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author：作者姓名
 * @Package：com.shop.product.service.impl
 * @Project：RuoYi-Cloudnew
 * @name：ItemServiceImpl
 * @Date：2024/6/5 19:34
 */
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private IPmsSkuInfoService skuInfoService;
    @Autowired
    private IPmsSkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private IPmsSkuImagesService skuImagesService;
    @Autowired
    private IPmsSpuInfoDescService spuInfoDescService;
    @Autowired
    private IPmsProductAttrValueService productAttrValueService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ItemInfo getItemBySkuId(Long skuId) throws ExecutionException, InterruptedException {

        ItemInfo itemInfo = new ItemInfo();
        //异步编排
        CompletableFuture<ItemInfo> itemInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            //1获取skuInfo
            PmsSkuInfo pmsSkuInfo = skuInfoService.selectPmsSkuInfoBySkuId(skuId);
            itemInfo.setItemSkuInfo(pmsSkuInfo);
            return itemInfo;
        },threadPoolExecutor);

        CompletableFuture<Void> itemSaleAttrValue = itemInfoCompletableFuture.thenCompose(itemInfo1 -> CompletableFuture.runAsync(() -> {
            //2获取销售属性信息
            List<ItemSaleAttr> itemSaleAttrBySpuId = skuSaleAttrValueService.getItemSaleAttrBySpuId(itemInfo1.getItemSkuInfo().getSpuId());
            itemInfo.setItemSaleAttrs(itemSaleAttrBySpuId);
//            return itemSaleAttrBySpuId;
        }));

        CompletableFuture<Void> itemImages = CompletableFuture.runAsync(() -> {
            //3获取sku图片信息
            List<PmsSkuImages> skuImagesBySkuId = skuImagesService.getSkuImagesBySkuId(skuId);
            itemInfo.setItemSkuImages(skuImagesBySkuId);
//            return skuImagesBySkuId;
        });

        CompletableFuture<Void> itemInfoDesc = itemInfoCompletableFuture.thenCompose(itemInfo1 -> CompletableFuture.runAsync(() -> {
            //4获取spu描述信息
            PmsSpuInfoDesc pmsSpuInfoDesc = spuInfoDescService.selectPmsSpuInfoDescBySpuId(itemInfo1.getItemSkuInfo().getSpuId());
            itemInfo.setItemSpuInfoDesc(pmsSpuInfoDesc);
//            return pmsSpuInfoDesc;
        }));


        CompletableFuture<Void> itemGroupBaseAttr = itemInfoCompletableFuture.thenCompose(itemInfo1 -> CompletableFuture.runAsync(() -> {
            //5获取spu基本属性信息
            List<ItemGroupBaseAttoVo> itemGroupBaseAttrByCatagoryId = productAttrValueService.getItemGroupBaseAttrByCatagoryId(itemInfo1.getItemSkuInfo().getCatalogId());
            itemInfo.setItemGroupBaseAttoVos(itemGroupBaseAttrByCatagoryId);
//            return itemGroupBaseAttrByCatagoryId;
        }));

        CompletableFuture.allOf(
                itemSaleAttrValue,
                itemImages,
                itemInfoDesc,
                itemGroupBaseAttr
        ).get();
        return itemInfo;
    }

    @Override
    public List<ShopCar> shopCarList(Long userId) {
        //1查找redis中是否存在购物车列表
        if (redisTemplate.hasKey(String.valueOf(userId))) {
            List<String> range = redisTemplate.opsForList().range(String.valueOf(userId), 0, -1);
            ArrayList<ShopCar> shopCars = new ArrayList<>();
            ObjectMapper objectMapper = new ObjectMapper();
            for (String json : range) {
                try {
                    ShopCar shopCar = objectMapper.readValue(json, ShopCar.class);
                    shopCars.add(shopCar);
                } catch (JsonProcessingException e) {
                    // 处理异常
                }
            }
            return shopCars;
        }
        //通过SQL语句查询购物车列表
        List<ShopCar>list=itemMapper.ShopCarList(userId);
        //将查询到的购物车列表存储到redis中
        for (ShopCar shopCar : list) {
            redisTemplate.opsForList().rightPush(String.valueOf(userId),JSON.toJSONString(shopCar));
            redisTemplate.expire(String.valueOf(userId),24, TimeUnit.HOURS);
        }
        return list;
    }

    @Override
    public void ShopCarAdd(ShopCarAndDetails shopCarAndDetails) {
        //判断是否存在购物车表
        List<ShopCar> list = itemMapper.ShopCarList(shopCarAndDetails.getUserId());
        if (list==null){
            itemMapper.ShopCarAdd(shopCarAndDetails);
        }
        //判断是否存在购物车明细表
        List<ShopCarDetails>list1=itemMapper.ShopCarDetailsList(shopCarAndDetails.getSkuId(),shopCarAndDetails.getCarId());
        if (list1==null){
            //添加购物车明细表
            itemMapper.ShopCarDetailsAdd(shopCarAndDetails);
        }else if (list1!=null){
            //修改购物车明细表的count
            itemMapper.updateShopCarDetailsCount(shopCarAndDetails);
        }
    }

    @Override
    public void ShopCarDetailsDel(Long detailsId) {
        itemMapper.ShopCarDetailsDel(detailsId);
    }

    @Override
    public Result ShopCarDetailsUpdate(ShopCarAndDetails shopCarAndDetails) {
        if (shopCarAndDetails.getDetailsCount()==1){
            return Result.error("无法继续减少");
        }
        itemMapper.ShopCarDetailsUpdate(shopCarAndDetails.getDetailsId(),shopCarAndDetails.getDetailsCount());
        return Result.success();
    }
}
